import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  DndContext,
  DragEndEvent,
  DragOverEvent,
  DragStartEvent,
  PointerSensor,
  KeyboardSensor,
  useSensor,
  useSensors,
  closestCorners,
  pointerWithin,
  DragOverlay,
  CollisionDetection,
} from '@dnd-kit/core'

import { ArrowLeft, Settings, Filter, RefreshCw, Calendar, Tag, BarChart3, TrendingUp, ChevronLeft, ChevronRight, Smartphone, Monitor, Clock } from 'lucide-react'
import { Task, TaskStatus, KanbanData } from '../types'
import { kanbanAPI } from '../services/kanbanAPI'
import { taskAPI } from '../services/api'
import KanbanColumn from '../components/KanbanColumn'
import KanbanTaskCard from '../components/KanbanTaskCard'
import LoadingSpinner from '../components/LoadingSpinner'


export default function KanbanPage() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(true)
  const [kanbanData, setKanbanData] = useState<KanbanData | null>(null)
  const [activeTask, setActiveTask] = useState<Task | null>(null)
  const [showFilterPanel, setShowFilterPanel] = useState(false)
  const [showSettings, setShowSettings] = useState(false)
  const [filterPriority, setFilterPriority] = useState<string>('all')
  const [filterCategory, setFilterCategory] = useState<string>('all')
  const [filterTime, setFilterTime] = useState<string>('all')
  const [filterTags, setFilterTags] = useState<string[]>([])
  const [filterHasSubtasks, setFilterHasSubtasks] = useState<string>('all')
  const [filterIsRecurring, setFilterIsRecurring] = useState<string>('all')
  const [showStatsPanel, setShowStatsPanel] = useState(false)
  const [isMobileView, setIsMobileView] = useState(false)
  const [currentMobileColumn, setCurrentMobileColumn] = useState(0)

  const [notification, setNotification] = useState<{message: string, type: 'success' | 'error'} | null>(null)
  const [isDragging, setIsDragging] = useState(false)

  // 拖拽传感器配置
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 3, // 减少激活距离，更容易触发拖拽
      },
    }),
    useSensor(KeyboardSensor)
  )

  // 自定义碰撞检测函数 - 优化拖拽精确度
  const customCollisionDetection: CollisionDetection = (args) => {
    // 首先尝试 pointerWithin (指针是否在容器内)
    const pointerCollisions = pointerWithin(args)

    if (pointerCollisions.length > 0) {
      // 优先选择列容器而不是任务
      const columnCollision = pointerCollisions.find(collision => 
        collision.data?.current?.type === 'column'
      )
      if (columnCollision) {
        return [columnCollision]
      }
      
      // 如果没有列碰撞，返回第一个碰撞
      return [pointerCollisions[0]]
    }

    // 如果指针碰撞没有结果，使用 closestCorners 作为后备
    return closestCorners(args)
  }

  useEffect(() => {
    loadKanbanData()
    
    // 检测屏幕尺寸
    const checkScreenSize = () => {
      const isMobile = window.innerWidth < 768 // md breakpoint
      setIsMobileView(isMobile)
    }
    
    checkScreenSize()
    window.addEventListener('resize', checkScreenSize)
    
    return () => window.removeEventListener('resize', checkScreenSize)
  }, [])



  const loadKanbanData = async () => {
    try {
      setLoading(true)
      const response = await kanbanAPI.getKanbanData()
      if (response.success) {
        // 确保 tasks 对象包含所有状态的数组
        const data = response.data
        const normalizedData = {
          ...data,
          tasks: {
            todo: data.tasks?.todo || [],
            in_progress: data.tasks?.in_progress || [],
            review: data.tasks?.review || [],
            done: data.tasks?.done || []
          }
        }
        setKanbanData(normalizedData)
      }
    } catch (error) {
      console.error('加载看板数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleDragStart = (event: DragStartEvent) => {
    const { active } = event
    const taskId = active.id as string
    
    // console.log('🚀 拖拽开始:', { taskId, isDragging })
    
    // 防止重复拖拽
    if (isDragging) {
      console.log('⚠️ 正在处理拖拽，跳过新的拖拽操作')
      return
    }
    
    setIsDragging(true)
    
    // 找到被拖拽的任务
    if (kanbanData) {
      for (const status in kanbanData.tasks) {
        const task = (kanbanData.tasks[status as TaskStatus] || []).find(t => t.id === taskId)
        if (task) {
          // console.log('✅ 找到拖拽任务:', { task: task.title, status })
          setActiveTask(task)
          break
        }
      }
    }
  }

  const handleDragOver = (event: DragOverEvent) => {
    const { active, over } = event
    
    if (!over || !kanbanData) return

    const activeId = active.id as string
    const overId = over.id as string

    // console.log('🔄 拖拽悬停:', { activeId, overId })

    // 如果拖拽到同一位置，不做任何操作
    if (activeId === overId) return

    // 只做视觉预览，不修改实际状态
    // 实际的状态更新在 handleDragEnd 中进行
  }

  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event
    
    // 清理拖拽状态
    setActiveTask(null)
    
    // 检查是否正在处理拖拽
    if (!isDragging) {
      console.log('⚠️ 非拖拽状态，跳过处理')
      return
    }

    if (!over || !kanbanData) {
      setIsDragging(false)
      return
    }

    const activeId = active.id as string
    const overId = over.id as string

    console.log('🔍 拖拽ID检查:', { 
      activeId, 
      overId, 
      areEqual: activeId === overId,
      activeIdType: typeof activeId,
      overIdType: typeof overId,
      activeData: active.data?.current,
      overData: over.data?.current,
      overRect: over.rect,
      activeRect: active.rect
    })

    // 如果拖拽到同一位置，不做任何操作
    if (activeId === overId) {
      console.log('📍 拖拽到同一位置，跳过处理')
      setIsDragging(false)
      return
    }

    console.log('🎯 开始处理拖拽结束:', { 
      activeId, 
      overId, 
      activeType: active.data?.current?.type,
      overType: over.data?.current?.type,
      overData: over.data?.current
    })

    try {
      // 1. 找到源任务的当前状态和位置
      let sourceStatus: TaskStatus | null = null
      let sourceIndex = -1
      let sourceTask: any = null

      for (const status in kanbanData.tasks) {
        const tasks = kanbanData.tasks[status as TaskStatus] || []
        const index = tasks.findIndex(task => task.id === activeId)
        if (index !== -1) {
          sourceStatus = status as TaskStatus
          sourceIndex = index
          sourceTask = tasks[index]
          break
        }
      }

      if (!sourceStatus || !sourceTask) {
        console.error('❌ 找不到源任务:', activeId)
        setIsDragging(false)
        return
      }

      // 2. 确定目标状态和位置
      let targetStatus: TaskStatus | null = null
      let targetIndex = -1

      if (['todo', 'in_progress', 'review', 'done'].includes(overId)) {
        // 拖拽到列上 - 放到列的末尾
        targetStatus = overId as TaskStatus
        targetIndex = (kanbanData.tasks[targetStatus] || []).length
        console.log('🎯 拖拽到列:', targetStatus)
      } else {
        // 拖拽到任务上 - 需要判断是否跨列移动
        for (const status in kanbanData.tasks) {
          const tasks = kanbanData.tasks[status as TaskStatus] || []
          const index = tasks.findIndex(task => task.id === overId)
          if (index !== -1) {
            targetStatus = status as TaskStatus
            targetIndex = index
            console.log('🎯 拖拽到任务:', { targetStatus, targetIndex, targetTaskId: overId })
            
            // 如果是跨列拖拽到任务上，将任务放到目标列的末尾而不是具体位置
            if (sourceStatus !== targetStatus) {
              targetIndex = (kanbanData.tasks[targetStatus] || []).length
              console.log('🔄 跨列拖拽，调整到列末尾:', targetIndex)
            }
            break
          }
        }
      }

      if (!targetStatus) {
        console.error('❌ 找不到目标位置:', overId)
        setIsDragging(false)
        return
      }

      // 3. 检查是否真的需要移动
      const isSameColumn = sourceStatus === targetStatus
      const isSamePosition = isSameColumn && Math.abs(sourceIndex - targetIndex) <= 1

      if (isSameColumn && isSamePosition) {
        console.log('📍 任务位置未发生实际变化，跳过更新')
        setIsDragging(false)
        return
      }

      console.log('📊 拖拽信息:', {
        源状态: sourceStatus,
        源位置: sourceIndex,
        目标状态: targetStatus,
        目标位置: targetIndex,
        任务: sourceTask.title
      })

      // 4. 计算最终位置（考虑同列内移动的位置调整）
      let finalPosition = targetIndex
      if (isSameColumn && sourceIndex < targetIndex) {
        // 同列内向后移动，目标位置需要减1（因为源任务会先被移除）
        finalPosition = targetIndex - 1
      }

      // 5. 调用API更新后端（不先更新本地状态，避免重复）
      console.log('🌐 调用API更新任务状态...')
      await kanbanAPI.updateTaskStatus(activeId, targetStatus, finalPosition)
      console.log('✅ API调用成功')

      // 6. API成功后，重新加载数据确保一致性
      await loadKanbanData()
      console.log('🔄 数据已重新加载')

      // 显示成功通知
      setNotification({
        message: `任务已移动到"${getStatusDisplayName(targetStatus)}"`,
        type: 'success'
      })
      
      // 3秒后清除通知
      setTimeout(() => setNotification(null), 3000)

    } catch (error) {
      console.error('❌ 拖拽处理失败:', error)
      
      // 失败时重新加载数据以确保状态一致
      await loadKanbanData()
      
      setNotification({
        message: '移动任务失败，请重试',
        type: 'error'
      })
      
      setTimeout(() => setNotification(null), 3000)
    } finally {
      // 无论成功失败，都要清除拖拽状态
      setIsDragging(false)
      console.log('🏁 拖拽处理完成')
    }
  }

  // 辅助函数：获取状态显示名称
  const getStatusDisplayName = (status: TaskStatus): string => {
    const statusMap = {
      'todo': '待处理',
      'in_progress': '进行中', 
      'review': '待审核',
      'done': '已完成'
    }
    return statusMap[status] || status
  }

  const handleTaskClick = (taskId: string) => {
    navigate(`/task/${taskId}`)
  }



  const handleRefresh = () => {
    loadKanbanData()
  }

  const handleFilter = () => {
    setShowFilterPanel(!showFilterPanel)
  }

  const handleSettings = () => {
    setShowSettings(!showSettings)
  }

  const handleStats = () => {
    setShowStatsPanel(!showStatsPanel)
  }

  // 移动端列切换
  const handleMobileColumnChange = (direction: 'prev' | 'next') => {
    const filteredData = getFilteredKanbanData()
    if (!filteredData) return
    
    const visibleColumns = filteredData.columns.filter(col => col.is_visible)
    if (visibleColumns.length === 0) return // 没有可见列时不处理
    
    const maxIndex = visibleColumns.length - 1
    
    if (direction === 'prev') {
      setCurrentMobileColumn(prev => prev > 0 ? prev - 1 : maxIndex)
    } else {
      setCurrentMobileColumn(prev => prev < maxIndex ? prev + 1 : 0)
    }
  }

  const toggleViewMode = () => {
    setIsMobileView(!isMobileView)
  }

  // 移动端触摸事件优化
  useEffect(() => {
    if (!isMobileView) return

    // 检查是否在看板页面
    const isKanbanPage = window.location.pathname.includes('/kanban') || window.location.pathname === '/'
    if (!isKanbanPage) {
      console.log('不在看板页面，跳过触摸事件绑定')
      return
    }

    // 使用整个移动端容器作为触摸区域，提供更大的触摸范围
    const touchContainer = document.querySelector('[data-touch-container="kanban"]')
    if (!touchContainer) {
      console.log('未找到看板触摸容器')
      return
    }

    let startX: number | null = null
    let startY: number | null = null
    let endX: number | null = null
    let isSwiping = false

    const handleTouchStart = (e: Event) => {
      const touchEvent = e as TouchEvent
      console.log('🖐️ 触摸开始:', { x: touchEvent.touches[0].clientX, y: touchEvent.touches[0].clientY })
      startX = touchEvent.touches[0].clientX
      startY = touchEvent.touches[0].clientY
      endX = null
      isSwiping = false
    }

    const handleTouchMove = (e: Event) => {
      const touchEvent = e as TouchEvent
      if (!startX || !startY) return
      
      endX = touchEvent.touches[0].clientX
      const endY = touchEvent.touches[0].clientY
      
      const deltaX = Math.abs(endX - startX)
      const deltaY = Math.abs(endY - startY)
      
      // 如果水平滑动距离大于垂直滑动且超过阈值，标记为滑动状态
      if (deltaX > deltaY && deltaX > 20) {
        isSwiping = true
        e.preventDefault()
        e.stopPropagation()
      }
    }

    const handleTouchEnd = () => {
      console.log('🖐️ 触摸结束:', { isSwiping, startX, endX })
      
      if (!startX || !endX || !isSwiping) {
        console.log('❌ 不是有效滑动')
        return
      }

      const distance = startX - endX
      const minSwipeDistance = 80 // 增加滑动距离阈值，更适合手机
      const isLeftSwipe = distance > minSwipeDistance
      const isRightSwipe = distance < -minSwipeDistance

      console.log('📏 滑动分析:', { 
        distance, 
        minSwipeDistance, 
        isLeftSwipe, 
        isRightSwipe,
        threshold: minSwipeDistance 
      })

      if (isLeftSwipe) {
        console.log('⬅️ 左滑 -> 下一列')
        handleMobileColumnChange('next')
      } else if (isRightSwipe) {
        console.log('➡️ 右滑 -> 上一列')
        handleMobileColumnChange('prev')
      }

      // 重置状态
      startX = null
      startY = null
      endX = null
      isSwiping = false
    }

    // 添加事件监听器，使用 capture 模式确保优先处理
    touchContainer.addEventListener('touchstart', handleTouchStart, { passive: false, capture: true })
    touchContainer.addEventListener('touchmove', handleTouchMove, { passive: false, capture: true })
    touchContainer.addEventListener('touchend', handleTouchEnd, { passive: true, capture: true })

    return () => {
      touchContainer.removeEventListener('touchstart', handleTouchStart, { capture: true })
      touchContainer.removeEventListener('touchmove', handleTouchMove, { capture: true })
      touchContainer.removeEventListener('touchend', handleTouchEnd, { capture: true })
    }
  }, [isMobileView, handleMobileColumnChange])



  // 清除所有筛选
  const clearAllFilters = () => {
    setFilterPriority('all')
    setFilterCategory('all')
    setFilterTime('all')
    setFilterTags([])
    setFilterHasSubtasks('all')
    setFilterIsRecurring('all')
  }

  // 检查是否有活跃的筛选
  const hasActiveFilters = () => {
    return filterPriority !== 'all' || 
           filterCategory !== 'all' || 
           filterTime !== 'all' || 
           filterTags.length > 0 ||
           filterHasSubtasks !== 'all' ||
           filterIsRecurring !== 'all'
  }

  // 切换标签筛选
  const toggleTagFilter = (tag: string) => {
    setFilterTags(prev => 
      prev.includes(tag) 
        ? prev.filter(t => t !== tag)
        : [...prev, tag]
    )
  }

  // 快速添加任务
  const handleQuickAddTask = async (status: TaskStatus, title: string) => {
    try {
      const newTask = {
        title,
        description: '',
        priority: 'P2' as const,
        category: 'other' as const,
        tags: [],
        status,
        dueDate: undefined,
        reminderMinutes: 30,
        notes: '',
        isRecurring: false,
        recurringType: 'daily' as const,
        recurringPattern: ''
      }

      await taskAPI.createTask(newTask)
      await loadKanbanData() // 重新加载数据
      
      setNotification({
        message: '任务添加成功！',
        type: 'success'
      })
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('添加任务失败:', error)
      setNotification({
        message: '添加任务失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  // 删除任务
  const handleDeleteTask = async (taskId: string) => {
    try {
      await taskAPI.deleteTask(taskId)
      await loadKanbanData() // 重新加载数据
      
      setNotification({
        message: '任务删除成功！',
        type: 'success'
      })
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('删除任务失败:', error)
      setNotification({
        message: '删除任务失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  // 移动任务到其他列
  const handleMoveTaskToColumn = async (taskId: string, newStatus: string) => {
    try {
      await taskAPI.updateTask(taskId, { status: newStatus })
      await loadKanbanData() // 重新加载数据
      
      setNotification({
        message: '任务移动成功！',
        type: 'success'
      })
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('移动任务失败:', error)
      setNotification({
        message: '移动任务失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  // 重命名列
  const handleRenameColumn = async (columnId: string, newTitle: string) => {
    try {
      await kanbanAPI.updateKanbanColumn(columnId, { title: newTitle })
      await loadKanbanData() // 重新加载数据
      
      setNotification({
        message: '列重命名成功！',
        type: 'success'
      })
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('重命名列失败:', error)
      setNotification({
        message: '重命名列失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  // 清空列
  const handleClearColumn = async (columnId: string) => {
    try {
      const column = kanbanData?.columns.find(col => col.id === columnId)
      if (!column) return
      
      const tasksToDelete = kanbanData?.tasks[column.status] || []
      
      // 批量删除任务
      await Promise.all(tasksToDelete.map(task => taskAPI.deleteTask(task.id)))
      await loadKanbanData() // 重新加载数据
      
      setNotification({
        message: `已清空"${column.title}"列中的 ${tasksToDelete.length} 个任务！`,
        type: 'success'
      })
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('清空列失败:', error)
      setNotification({
        message: '清空列失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  // 切换列可见性
  const handleToggleColumnVisibility = async (columnId: string, currentVisibility: boolean) => {
    try {
      console.log('切换列可见性:', columnId, '当前状态:', currentVisibility, '→', !currentVisibility)
      
      const response = await kanbanAPI.updateKanbanColumn(columnId, {
        is_visible: !currentVisibility
      })
      
      console.log('API响应:', response)
      
      if (response.success) {
        // 如果要隐藏当前移动端显示的列，需要调整索引
        if (isMobileView && !currentVisibility === false && kanbanData) {
          const visibleColumns = kanbanData.columns
            .filter(column => column.is_visible)
            .sort((a, b) => a.column_order - b.column_order)
          
          const currentColumnIndex = visibleColumns.findIndex(col => col.id === columnId)
          if (currentColumnIndex === currentMobileColumn) {
            // 当前列将被隐藏，调整到下一个可见列或第一个列
            const newVisibleColumns = visibleColumns.filter(col => col.id !== columnId)
            if (newVisibleColumns.length > 0) {
              const newIndex = Math.min(currentMobileColumn, newVisibleColumns.length - 1)
              setCurrentMobileColumn(newIndex)
            } else {
              setCurrentMobileColumn(0)
            }
          } else if (currentColumnIndex < currentMobileColumn) {
            // 隐藏的列在当前列之前，需要调整索引
            setCurrentMobileColumn(prev => Math.max(0, prev - 1))
          }
        }
        
        // 更新本地状态
        setKanbanData(prev => {
          if (!prev) return prev
          
          const newData = {
            ...prev,
            columns: prev.columns.map(col => 
              col.id === columnId 
                ? { ...col, is_visible: !currentVisibility }
                : col
            )
          }
          
          console.log('更新后的列状态:', newData.columns.find(c => c.id === columnId))
          return newData
        })
        
        // 显示成功提示
        const statusText = !currentVisibility ? '显示' : '隐藏'
        const columnTitle = kanbanData?.columns.find(c => c.id === columnId)?.title || '列'
        setNotification({
          message: `${columnTitle}已${statusText}`,
          type: 'success'
        })
        
        // 3秒后自动消失
        setTimeout(() => setNotification(null), 3000)
      } else {
        throw new Error(response.message || '更新失败')
      }
    } catch (error) {
      console.error('切换列可见性失败:', error)
      setNotification({
        message: '操作失败，请重试: ' + (error as Error).message,
        type: 'error'
      })
      
      // 5秒后自动消失
      setTimeout(() => setNotification(null), 5000)
    }
  }

  // 重置布局
  const handleResetLayout = () => {
    if (confirm('确定要重置看板布局吗？这将恢复所有列的默认设置。')) {
      // TODO: 实现重置布局功能
      console.log('重置布局')
      alert('重置功能开发中...')
    }
  }

  // 导出数据
  const handleExportData = () => {
    if (!kanbanData) return
    
    try {
      const exportData = {
        exportTime: new Date().toISOString(),
        columns: kanbanData.columns,
        tasks: kanbanData.tasks,
        summary: {
          totalTasks: Object.values(kanbanData.tasks).flat().length,
          tasksByStatus: Object.entries(kanbanData.tasks).map(([status, tasks]) => ({
            status,
            count: tasks.length
          }))
        }
      }
      
      const dataStr = JSON.stringify(exportData, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      
      const link = document.createElement('a')
      link.href = URL.createObjectURL(dataBlob)
      link.download = `kanban-data-${new Date().toISOString().split('T')[0]}.json`
      link.click()
      
      URL.revokeObjectURL(link.href)
    } catch (error) {
      console.error('导出数据失败:', error)
      alert('导出失败，请重试')
    }
  }

  // 时间筛选辅助函数
  const isTaskInTimeRange = (task: Task, timeFilter: string): boolean => {
    if (timeFilter === 'all') return true
    
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const weekEnd = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
    
    if (!task.dueDate) {
      return timeFilter === 'no_due_date'
    }
    
    const taskDueDate = new Date(task.dueDate)
    const taskDate = new Date(taskDueDate.getFullYear(), taskDueDate.getMonth(), taskDueDate.getDate())
    
    switch (timeFilter) {
      case 'today':
        return taskDate.getTime() === today.getTime()
      case 'tomorrow':
        return taskDate.getTime() === tomorrow.getTime()
      case 'this_week':
        return taskDate >= today && taskDate <= weekEnd
      case 'overdue':
        return taskDate < today
      case 'no_due_date':
        return !task.dueDate
      default:
        return true
    }
  }

  // 获取所有可用标签
  const getAllTags = (): string[] => {
    if (!kanbanData) return []
    const allTasks = Object.values(kanbanData.tasks).flat()
    const tagSet = new Set<string>()
    allTasks.forEach(task => {
      if (task.tags && Array.isArray(task.tags)) {
        task.tags.forEach(tag => tagSet.add(tag))
      }
    })
    return Array.from(tagSet).sort()
  }

  // 筛选任务
  const filterTasks = (tasks: Task[]) => {
    return tasks.filter(task => {
      const priorityMatch = filterPriority === 'all' || task.priority === filterPriority
      const categoryMatch = filterCategory === 'all' || task.category === filterCategory
      const timeMatch = isTaskInTimeRange(task, filterTime)
      
      const tagsMatch = filterTags.length === 0 || 
        (task.tags && Array.isArray(task.tags) && 
         filterTags.some(tag => task.tags.includes(tag)))
      
      const subtasksMatch = filterHasSubtasks === 'all' ||
        (filterHasSubtasks === 'has_subtasks' && task.subtasks && task.subtasks.length > 0) ||
        (filterHasSubtasks === 'no_subtasks' && (!task.subtasks || task.subtasks.length === 0))
      
      const recurringMatch = filterIsRecurring === 'all' ||
        (filterIsRecurring === 'recurring' && task.isRecurring) ||
        (filterIsRecurring === 'non_recurring' && !task.isRecurring)
      
      return priorityMatch && categoryMatch && timeMatch && tagsMatch && subtasksMatch && recurringMatch
    })
  }

  // 获取筛选后的看板数据
  const getFilteredKanbanData = () => {
    if (!kanbanData) return null
    
    const filteredData = {
      ...kanbanData,
      tasks: {
        todo: filterTasks(kanbanData.tasks.todo || []),
        in_progress: filterTasks(kanbanData.tasks.in_progress || []),
        review: filterTasks(kanbanData.tasks.review || []),
        done: filterTasks(kanbanData.tasks.done || [])
      }
    }
    
    return filteredData
  }

  // 计算看板统计数据
  const getKanbanStats = () => {
    const filteredData = getFilteredKanbanData()
    if (!filteredData) return null

    const allTasks = Object.values(filteredData.tasks).flat()
    const totalTasks = allTasks.length
    const completedTasks = filteredData.tasks.done.length
    const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0

    // 优先级分布
    const priorityStats = {
      P0: allTasks.filter(t => t.priority === 'P0').length,
      P1: allTasks.filter(t => t.priority === 'P1').length,
      P2: allTasks.filter(t => t.priority === 'P2').length,
      P3: allTasks.filter(t => t.priority === 'P3').length,
    }

    // 时间统计
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const overdueTasks = allTasks.filter(task => {
      if (!task.dueDate) return false
      const dueDate = new Date(task.dueDate)
      const dueDateOnly = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate())
      return dueDateOnly < today
    }).length

    const todayTasks = allTasks.filter(task => {
      if (!task.dueDate) return false
      const dueDate = new Date(task.dueDate)
      const dueDateOnly = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate())
      return dueDateOnly.getTime() === today.getTime()
    }).length

    // 分类统计
    const categoryStats = {
      work: allTasks.filter(t => t.category === 'work').length,
      personal: allTasks.filter(t => t.category === 'personal').length,
      learning: allTasks.filter(t => t.category === 'learning').length,
      health: allTasks.filter(t => t.category === 'health').length,
      other: allTasks.filter(t => t.category === 'other').length,
    }

    return {
      totalTasks,
      completedTasks,
      completionRate,
      columnStats: {
        todo: filteredData.tasks.todo.length,
        in_progress: filteredData.tasks.in_progress.length,
        review: filteredData.tasks.review.length,
        done: filteredData.tasks.done.length,
      },
      priorityStats,
      timeStats: {
        overdue: overdueTasks,
        today: todayTasks,
      },
      categoryStats
    }
  }

  if (loading) {
    return <LoadingSpinner size="lg" text="加载看板数据中..." fullScreen />
  }

  if (!kanbanData) {
    return (
      <div className="min-h-screen bg-theme-bg-secondary flex items-center justify-center">
        <div className="text-center">
          <p className="text-theme-text-secondary mb-4">加载看板数据失败</p>
          <button
            onClick={handleRefresh}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 顶部导航 */}
      {isMobileView ? (
        // 移动端简洁头部
        <div className="bg-theme-bg border-b border-theme-border">
          {/* 主头部行 */}
          <div className="flex items-center justify-between px-4 py-3">
            <div className="flex items-center gap-3">
              <button
                onClick={() => navigate('/')}
                className="p-2 hover:bg-theme-bg-tertiary rounded-lg transition-colors"
              >
                <ArrowLeft className="w-5 h-5 text-theme-text-secondary" />
              </button>
              <div className="flex items-baseline gap-2">
                <h1 className="text-lg font-semibold text-theme-text">看板</h1>
                <span className="text-sm text-theme-text-secondary">
                  {(() => {
                    const filteredData = getFilteredKanbanData()
                    if (!filteredData) return '0 个任务'
                    const taskCount = Object.values(filteredData.tasks).flat().length
                    return `${taskCount} 个任务`
                  })()}
                </span>
                {hasActiveFilters() && (
                  <span className="px-1.5 py-0.5 bg-orange-100 text-orange-600 text-xs rounded-md">
                    已筛选
                  </span>
                )}
              </div>
            </div>
            
            <div className="flex items-center gap-1">
              <button
                onClick={handleFilter}
                className={`p-2.5 rounded-xl transition-all ${
                  showFilterPanel || hasActiveFilters()
                    ? 'bg-blue-100 text-blue-600 shadow-sm' 
                    : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title="筛选"
              >
                <Filter className="w-4 h-4" />
              </button>
              <button
                onClick={handleSettings}
                className={`p-2.5 rounded-xl transition-all ${
                  showSettings 
                    ? 'bg-blue-100 text-blue-600 shadow-sm' 
                    : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title="更多"
              >
                <Settings className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      ) : (
        // 桌面端完整头部
        <div className="bg-theme-bg border-b border-theme-border px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <button
                onClick={() => navigate('/')}
                className="p-2 hover:bg-theme-bg-tertiary rounded-lg transition-colors"
              >
                <ArrowLeft className="w-5 h-5 text-theme-text-secondary" />
              </button>
              <h1 className="text-xl font-bold text-theme-text">看板视图</h1>
              <span className="px-2 py-1 bg-blue-100 text-blue-800 text-sm rounded-full">
                {(() => {
                  const filteredData = getFilteredKanbanData()
                  if (!filteredData) return 0
                  return Object.values(filteredData.tasks).flat().length
                })()} 个任务
              </span>
              
              {hasActiveFilters() && (
                <span className="px-2 py-1 bg-orange-100 text-orange-800 text-xs rounded-full">
                  已筛选
                </span>
              )}
            </div>

            <div className="flex items-center gap-2">
              <button
                onClick={handleRefresh}
                className="p-2 hover:bg-theme-bg-tertiary rounded-lg transition-colors"
                title="刷新数据"
              >
                <RefreshCw className="w-5 h-5 text-theme-text-secondary" />
              </button>
              <button
                onClick={toggleViewMode}
                className={`p-2 rounded-lg transition-colors ${
                  isMobileView ? 'bg-purple-100 text-purple-600' : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title={isMobileView ? "切换到网格视图" : "切换到移动视图"}
              >
                {isMobileView ? <Monitor className="w-5 h-5" /> : <Smartphone className="w-5 h-5" />}
              </button>
              <button
                onClick={handleStats}
                className={`p-2 rounded-lg transition-colors ${
                  showStatsPanel ? 'bg-green-100 text-green-600' : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title="统计"
              >
                <BarChart3 className="w-5 h-5" />
              </button>
              <button
                onClick={handleFilter}
                className={`p-2 rounded-lg transition-colors ${
                  showFilterPanel ? 'bg-blue-100 text-blue-600' : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title="筛选"
              >
                <Filter className="w-5 h-5" />
              </button>
              <button
                onClick={handleSettings}
                className={`p-2 rounded-lg transition-colors ${
                  showSettings ? 'bg-blue-100 text-blue-600' : 'hover:bg-theme-bg-tertiary text-theme-text-secondary'
                }`}
                title="设置"
              >
                <Settings className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 筛选面板 */}
      {showFilterPanel && (
        <div className="bg-theme-bg border-b border-theme-border px-4 py-3">
          <div className="space-y-4">
            {/* 移动端快速时间筛选 */}
            <div className="md:hidden">
              <div className="flex flex-wrap gap-2">
                {[
                  { value: 'all', label: '全部', icon: '📋' },
                  { value: 'overdue', label: '已逾期', icon: '🔴' },
                  { value: 'today', label: '今天', icon: '📅' },
                  { value: 'tomorrow', label: '明天', icon: '📆' },
                  { value: 'this_week', label: '本周', icon: '🗓️' },
                  { value: 'no_due_date', label: '无期限', icon: '⏰' }
                ].map(option => (
                  <button
                    key={option.value}
                    onClick={() => setFilterTime(option.value)}
                    className={`px-3 py-1.5 text-xs rounded-full transition-colors flex items-center gap-1 ${
                      filterTime === option.value
                        ? 'bg-blue-100 text-blue-700 border border-blue-300'
                        : 'bg-theme-bg-secondary text-theme-text-secondary border border-theme-border hover:bg-theme-bg-tertiary'
                    }`}
                  >
                    <span>{option.icon}</span>
                    {option.label}
                  </button>
                ))}
              </div>
            </div>
            
            <div className="flex items-center gap-4 flex-wrap">
              {/* PC端时间筛选 */}
              <div className="hidden md:flex items-center gap-2">
                <span className="text-sm font-medium text-theme-text-secondary flex items-center gap-1">
                  <Calendar size={14} />
                  时间:
                </span>
                <select 
                  value={filterTime}
                  onChange={(e) => setFilterTime(e.target.value)}
                  className="px-3 py-1 border border-theme-border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="all">全部时间</option>
                  <option value="overdue">🔴 已逾期</option>
                  <option value="today">📅 今天到期</option>
                  <option value="tomorrow">📆 明天到期</option>
                  <option value="this_week">🗓️ 本周到期</option>
                  <option value="no_due_date">⏰ 无截止时间</option>
                </select>
              </div>
              
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-theme-text-secondary">优先级:</span>
                <select 
                  value={filterPriority}
                  onChange={(e) => setFilterPriority(e.target.value)}
                  className="px-3 py-1 border border-theme-border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="all">全部</option>
                  <option value="P0">🔴 P0 - 紧急</option>
                  <option value="P1">🟠 P1 - 高</option>
                  <option value="P2">🟡 P2 - 中</option>
                  <option value="P3">🟢 P3 - 低</option>
                </select>
              </div>
              
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-theme-text-secondary">分类:</span>
                <select 
                  value={filterCategory}
                  onChange={(e) => setFilterCategory(e.target.value)}
                  className="px-3 py-1 border border-theme-border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="all">全部</option>
                  <option value="work">💼 工作</option>
                  <option value="personal">👤 个人</option>
                  <option value="learning">📚 学习</option>
                  <option value="health">🏃 健康</option>
                  <option value="other">📂 其他</option>
                </select>
              </div>
            </div>
            
            {/* 标签筛选 */}
            {getAllTags().length > 0 && (
              <div className="space-y-2">
                <span className="text-sm font-medium text-theme-text-secondary flex items-center gap-1">
                  <Tag size={14} />
                  标签:
                </span>
                <div className="flex flex-wrap gap-2">
                  {getAllTags().map(tag => (
                    <button
                      key={tag}
                      onClick={() => toggleTagFilter(tag)}
                      className={`px-2 py-1 text-xs rounded-full transition-colors ${
                        filterTags.includes(tag)
                          ? 'bg-blue-100 text-blue-700 border border-blue-300'
                          : 'bg-theme-bg-secondary text-theme-text-secondary border border-theme-border hover:bg-theme-bg-tertiary'
                      }`}
                    >
                      #{tag}
                    </button>
                  ))}
                </div>
              </div>
            )}
            
            <button
              onClick={clearAllFilters}
              className="px-3 py-1 text-sm text-theme-text-secondary hover:text-theme-text border border-theme-border rounded hover:bg-theme-bg-secondary transition-colors"
            >
              清除筛选
            </button>
          </div>
        </div>
      )}

      {/* 统计面板 */}
      {showStatsPanel && (() => {
        const stats = getKanbanStats()
        if (!stats) return null
        
        return (
          <div className="bg-theme-bg border-b border-theme-border">
            <div className="px-4 py-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
                  <TrendingUp size={16} />
                  看板统计
                </h3>
                <button
                  onClick={() => setShowStatsPanel(false)}
                  className="p-1 hover:bg-theme-bg-secondary rounded"
                >
                  ×
                </button>
              </div>
              
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                {/* 总体统计 */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                  <div className="text-2xl font-bold text-blue-600">{stats.totalTasks}</div>
                  <div className="text-xs text-blue-700">总任务数</div>
                </div>
                <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                  <div className="text-2xl font-bold text-green-600">{stats.completedTasks}</div>
                  <div className="text-xs text-green-700">已完成</div>
                </div>
                <div className="bg-purple-50 border border-purple-200 rounded-lg p-3">
                  <div className="text-2xl font-bold text-purple-600">{stats.completionRate}%</div>
                  <div className="text-xs text-purple-700">完成率</div>
                </div>
                <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                  <div className="text-2xl font-bold text-red-600">{stats.timeStats.overdue}</div>
                  <div className="text-xs text-red-700">已逾期</div>
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* 列统计 */}
                <div className="bg-theme-bg-secondary rounded-lg p-3">
                  <h4 className="text-xs font-semibold text-theme-text-secondary mb-2">各列分布</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">待处理</span>
                      <span className="text-sm font-medium text-slate-600">{stats.columnStats.todo}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">进行中</span>
                      <span className="text-sm font-medium text-blue-600">{stats.columnStats.in_progress}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">待审核</span>
                      <span className="text-sm font-medium text-orange-600">{stats.columnStats.review}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">已完成</span>
                      <span className="text-sm font-medium text-green-600">{stats.columnStats.done}</span>
                    </div>
                  </div>
                </div>
                
                {/* 优先级统计 */}
                <div className="bg-theme-bg-secondary rounded-lg p-3">
                  <h4 className="text-xs font-semibold text-theme-text-secondary mb-2">优先级分布</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-red-600">🔴 P0 - 紧急</span>
                      <span className="text-sm font-medium">{stats.priorityStats.P0}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-orange-600">🟠 P1 - 高</span>
                      <span className="text-sm font-medium">{stats.priorityStats.P1}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-yellow-600">🟡 P2 - 中</span>
                      <span className="text-sm font-medium">{stats.priorityStats.P2}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-green-600">🟢 P3 - 低</span>
                      <span className="text-sm font-medium">{stats.priorityStats.P3}</span>
                    </div>
                  </div>
                </div>
                
                {/* 分类统计 */}
                <div className="bg-theme-bg-secondary rounded-lg p-3">
                  <h4 className="text-xs font-semibold text-theme-text-secondary mb-2">分类分布</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">💼 工作</span>
                      <span className="text-sm font-medium">{stats.categoryStats.work}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">👤 个人</span>
                      <span className="text-sm font-medium">{stats.categoryStats.personal}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">📚 学习</span>
                      <span className="text-sm font-medium">{stats.categoryStats.learning}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">🏃 健康</span>
                      <span className="text-sm font-medium">{stats.categoryStats.health}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-theme-text">📂 其他</span>
                      <span className="text-sm font-medium">{stats.categoryStats.other}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )
      })()}

      {/* 设置面板 */}
      {showSettings && (
        <div className="bg-theme-bg border-b border-theme-border px-4 py-4">
          <div className="space-y-4">
            {/* 移动端专用快捷操作 */}
            {isMobileView && (
              <div className="pb-4 border-b border-theme-border">
                <h3 className="text-sm font-medium text-theme-text mb-3">快捷操作</h3>
                <div className="grid grid-cols-3 gap-3">
                  <button
                    onClick={handleRefresh}
                    className="flex flex-col items-center gap-2 p-3 rounded-lg hover:bg-theme-bg-secondary transition-colors"
                  >
                    <RefreshCw className="w-5 h-5 text-theme-text-secondary" />
                    <span className="text-xs text-theme-text-secondary">刷新</span>
                  </button>
                  <button
                    onClick={toggleViewMode}
                    className={`flex flex-col items-center gap-2 p-3 rounded-lg transition-colors ${
                      !isMobileView ? 'bg-purple-100 text-purple-600' : 'hover:bg-theme-bg-secondary text-theme-text-secondary'
                    }`}
                  >
                    <Monitor className="w-5 h-5" />
                    <span className="text-xs">网格视图</span>
                  </button>
                  <button
                    onClick={handleStats}
                    className={`flex flex-col items-center gap-2 p-3 rounded-lg transition-colors ${
                      showStatsPanel ? 'bg-green-100 text-green-600' : 'hover:bg-theme-bg-secondary text-theme-text-secondary'
                    }`}
                  >
                    <BarChart3 className="w-5 h-5" />
                    <span className="text-xs">统计</span>
                  </button>
                </div>
              </div>
            )}
            
            <div>
              <h3 className="text-sm font-medium text-theme-text mb-1">列显示设置</h3>
              <p className="text-xs text-theme-text-muted mb-3">控制哪些状态列在看板中显示。隐藏的列不会显示在看板上，但数据仍然保留。</p>
              
              <div className="grid grid-cols-2 gap-3">
                {kanbanData?.columns.map((column) => (
                  <div key={column.id} className="flex items-center justify-between p-3 border border-theme-border rounded-lg hover:bg-theme-bg-secondary transition-colors">
                    <div className="flex items-center gap-2">
                      <div 
                        className="w-3 h-3 rounded-full flex-shrink-0"
                        style={{ backgroundColor: column.color }}
                      />
                      <span className="text-sm text-theme-text-secondary font-medium">{column.title}</span>
                      <span className="text-xs text-slate-400">({(kanbanData.tasks[column.status] || []).length})</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <label className="flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={column.is_visible}
                          onChange={() => handleToggleColumnVisibility(column.id, column.is_visible)}
                          className="w-4 h-4 text-blue-600 border-theme-border rounded focus:ring-blue-500 focus:ring-2"
                        />
                        <span className="ml-2 text-xs text-theme-text-secondary select-none">
                          {column.is_visible ? '显示' : '隐藏'}
                        </span>
                      </label>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            
            <div className="pt-3 border-t border-slate-100">
              <h4 className="text-sm font-medium text-theme-text mb-2">快捷操作</h4>
              <div className="flex items-center gap-2">
                <button 
                  onClick={handleResetLayout}
                  className="flex items-center gap-1 px-3 py-2 text-sm text-blue-600 hover:text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors"
                  title="恢复所有列的默认设置"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  重置布局
                </button>
                <button 
                  onClick={handleExportData}
                  className="flex items-center gap-1 px-3 py-2 text-sm text-theme-text-secondary hover:text-theme-text-secondary border border-theme-border rounded-lg hover:bg-theme-bg-secondary transition-colors"
                  title="导出看板数据为JSON文件"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  导出数据
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 通知提示 */}
      {notification && (
        <div className={`fixed top-4 right-4 z-[60] px-4 py-3 rounded-lg shadow-lg transition-all duration-300 ${
          notification.type === 'success' 
            ? 'bg-green-500 text-white' 
            : 'bg-red-500 text-white'
        }`}>
          <div className="flex items-center gap-2">
            {notification.type === 'success' ? (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            ) : (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            )}
            <span className="text-sm font-medium">{notification.message}</span>
            <button
              onClick={() => setNotification(null)}
              className="ml-2 hover:bg-theme-bg/20 rounded p-1 transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* 看板主体 */}
      <div className="p-4 sm:p-6 lg:p-8">
        <DndContext
          sensors={sensors}
          collisionDetection={customCollisionDetection}
          onDragStart={handleDragStart}
          onDragOver={handleDragOver}
          onDragEnd={handleDragEnd}
        >
          {isMobileView ? (
            /* 移动端单列视图 */
            <div 
              className="space-y-4"
              data-touch-container="kanban"
              style={{ touchAction: 'pan-y pinch-zoom' }}
            >
              {(() => {
                const filteredData = getFilteredKanbanData()
                if (!filteredData) return null
                
                const visibleColumns = filteredData.columns
                  .filter(column => column.is_visible)
                  .sort((a, b) => a.column_order - b.column_order)
                
                if (visibleColumns.length === 0) {
                  return (
                    <div className="text-center py-12">
                      <div className="text-theme-text-secondary mb-4">
                        <Clock className="w-12 h-12 mx-auto mb-2 opacity-50" />
                        <p>没有可见的列</p>
                        <p className="text-sm">请在设置中显示至少一个列</p>
                      </div>
                    </div>
                  )
                }
                
                // 确保当前索引在有效范围内
                const safeIndex = Math.min(currentMobileColumn, visibleColumns.length - 1)
                const currentColumn = visibleColumns[safeIndex]
                
                // 如果索引被调整了，更新状态
                if (safeIndex !== currentMobileColumn) {
                  setCurrentMobileColumn(safeIndex)
                }
                
                if (!currentColumn) return null
                
                return (
                  <>
                    {/* 移动端列导航 */}
                    <div className="bg-theme-bg rounded-xl p-4 shadow-sm border border-theme-border mb-4">
                      <div className="flex items-center justify-between mb-3">
                        <button
                          onClick={() => handleMobileColumnChange('prev')}
                          className="p-2 hover:bg-theme-bg-secondary rounded-lg transition-colors disabled:opacity-50"
                          disabled={visibleColumns.length <= 1}
                        >
                          <ChevronLeft className="w-5 h-5 text-theme-text-secondary" />
                        </button>
                        
                        <div className="flex-1 text-center">
                          <div className="flex items-center justify-center gap-2 mb-1">
                            <div 
                              className="w-3 h-3 rounded-full flex-shrink-0"
                              style={{ backgroundColor: currentColumn.color }}
                            />
                            <h2 className="text-lg font-semibold text-theme-text">{currentColumn.title}</h2>
                          </div>
                          <div className="flex items-center justify-center gap-3">
                            <span className="text-sm text-theme-text-secondary">
                              {currentMobileColumn + 1} / {visibleColumns.length}
                            </span>
                            <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                              {filteredData.tasks[currentColumn.status]?.length || 0} 个任务
                            </span>
                          </div>
                        </div>
                        
                        <button
                          onClick={() => handleMobileColumnChange('next')}
                          className="p-2 hover:bg-theme-bg-secondary rounded-lg transition-colors disabled:opacity-50"
                          disabled={visibleColumns.length <= 1}
                        >
                          <ChevronRight className="w-5 h-5 text-theme-text-secondary" />
                        </button>
                      </div>
                      
                      {/* 进度指示器 */}
                      {visibleColumns.length > 1 && (
                        <div className="flex items-center justify-center gap-1">
                          {visibleColumns.map((_, index) => (
                            <button
                              key={index}
                              onClick={() => setCurrentMobileColumn(index)}
                              className={`w-2 h-2 rounded-full transition-all ${
                                index === currentMobileColumn 
                                  ? 'bg-blue-500 w-6' 
                                  : 'bg-theme-border hover:bg-theme-text-secondary'
                              }`}
                            />
                          ))}
                        </div>
                      )}
                    </div>
                    
                                         {/* 当前列内容 */}
                     <div className="w-full">
                      <KanbanColumn
                        key={currentColumn.id}
                        column={{
                          ...currentColumn,
                          taskCount: filteredData.tasks[currentColumn.status]?.length || 0
                        }}
                        tasks={filteredData.tasks[currentColumn.status] || []}
                        onTaskClick={handleTaskClick}
                        onDeleteTask={handleDeleteTask}
                        onAddTask={handleQuickAddTask}
                        onRenameColumn={handleRenameColumn}
                        onClearColumn={handleClearColumn}
                        onColumnSettings={(columnId) => {
                          const col = filteredData.columns.find(c => c.id === columnId)
                          if (col) {
                            handleToggleColumnVisibility(columnId, col.is_visible)
                          }
                        }}
                        onMoveTaskToColumn={handleMoveTaskToColumn}
                        availableColumns={filteredData.columns.filter(col => col.is_visible).map(col => ({
                          id: col.id,
                          title: col.title,
                          status: col.status,
                          color: col.color
                        }))}
                        isMobileView={isMobileView}
                      />
                    </div>
                  </>
                )
              })()}
            </div>
          ) : (
            /* 桌面端网格视图 */
            <div className="grid grid-cols-2 landscape:grid-cols-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
              {(() => {
                const filteredData = getFilteredKanbanData()
                if (!filteredData) return null
                
                return filteredData.columns
                  .filter(column => column.is_visible)
                  .sort((a, b) => a.column_order - b.column_order)
                  .map((column) => (
                    <KanbanColumn
                      key={column.id}
                      column={{
                        ...column,
                        taskCount: filteredData.tasks[column.status]?.length || 0
                      }}
                      tasks={filteredData.tasks[column.status] || []}
                      onTaskClick={handleTaskClick}
                      onDeleteTask={handleDeleteTask}
                      onAddTask={handleQuickAddTask}
                      onRenameColumn={handleRenameColumn}
                      onClearColumn={handleClearColumn}
                      onColumnSettings={(columnId) => {
                        const col = filteredData.columns.find(c => c.id === columnId)
                        if (col) {
                          handleToggleColumnVisibility(columnId, col.is_visible)
                        }
                      }}
                      onMoveTaskToColumn={handleMoveTaskToColumn}
                      availableColumns={filteredData.columns.filter(col => col.is_visible).map(col => ({
                        id: col.id,
                        title: col.title,
                        status: col.status,
                        color: col.color
                      }))}
                      isMobileView={isMobileView}
                    />
                  ))
              })()}
            </div>
          )}

          {/* 拖拽预览 */}
          <DragOverlay>
            {activeTask ? (
              <KanbanTaskCard
                task={activeTask}
                onClick={() => {}}
                isDragging
              />
            ) : null}
          </DragOverlay>
        </DndContext>
      </div>


    </div>
  )
}
